package org.jwt.oauth.controller;

import java.util.Map;

import org.jwt.oauth.exception.ServiceErrorStatus;
import org.jwt.oauth.exception.ServiceRunTimeException;
import org.jwt.oauth.response.ResponseData;
import org.jwt.oauth.service.FusionTokenCrudService;
import org.jwt.oauth.tools.FusionTokenTools;
import org.jwt.oauth.user.FusionLoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FusionLoginController {

	@Autowired
	private FusionTokenCrudService tokenCrudService;

	@PostMapping("loginRefresh")
	public ResponseData<Object> refreshToken(@RequestBody FusionLoginInfo fusionLoginInfo) throws Exception {
		String refreshToken = fusionLoginInfo.getRefreshToken();
		Map<String, Object> tokeMap = tokenCrudService.refreshToken(refreshToken);
		return ResponseData.SUCCESS(tokeMap);
	}

	@GetMapping("loginError")
	public ResponseData<Object> loginError() {
		throw new ServiceRunTimeException(ServiceErrorStatus.AUTHENTICATION_FAILED);
	}

	@PostMapping("loginExit")
	public ResponseData<Object> tokenLogout() {
		String tokenValue = FusionTokenTools.getTokenValue();
		Boolean deleteToken = tokenCrudService.deleteToken(tokenValue);
		return ResponseData.SUCCESS(deleteToken);
	}

	@PostMapping("loginUser")
	public ResponseData<Object> loginUser(@RequestBody FusionLoginInfo fusionLoginInfo) {
		String username = fusionLoginInfo.getUsername();
		String password = fusionLoginInfo.getPassword();
		String type = fusionLoginInfo.getType();
		Object resultData = tokenCrudService.loginUser(username, password, type);
		return ResponseData.SUCCESS(resultData);
	}
}
